//
//  AddGroupChatViewController.m
//  PigMarket
//
//  Created by mac on 2019/6/17.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AddGroupChatViewController.h"
#import "AddGroupChatCell.h"
#import "AddGroupHeaderView.h"
#import <TIMComm.h>
#import <TIMConversation.h>
#import "ChatViewController.h"
@interface AddGroupChatViewController ()<UITableViewDelegate,UITableViewDataSource>
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 导航完成BtncompleteBtn
 */
@property (nonatomic , strong) UIButton *completeBtn;
/**
 headerView
 */
@property (nonatomic , strong) AddGroupHeaderView *headerView;
/**
 选中数组
 */
@property (nonatomic , strong) NSMutableArray *selectArr;
@end

@implementation AddGroupChatViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    switch (self.groupMemberHandelType) {
        case GroupMemberHandelTypeCreate:
            self.title = @"选择群聊";

            break;
        case GroupMemberHandelTypeAdd:
            self.title = @"添加群员";
            
            break;
        case GroupMemberHandelTypeDelete:
            self.title = @"删除群员";
            break;
        default:
            break;
    }
    [self setUpNav];
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - init method
- (void)setUpNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];

    self.completeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 56 * [JTool getScreenWidthScale], 26)];
    [self.completeBtn setTitle:@"完成" forState:UIControlStateNormal];
    self.completeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.completeBtn.backgroundColor = [UIColor primaryColor];
    self.completeBtn.layer.cornerRadius = 5;
    self.completeBtn.layer.masksToBounds = YES;
    [self.completeBtn addTarget:self action:@selector(completeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithCustomView:self.completeBtn];
    self.navigationItem.rightBarButtonItem = saveItem;
}
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void) initAction {
    
}

- (void)initData {
    
    switch (self.groupMemberHandelType) {
        case GroupMemberHandelTypeCreate:
        {
            [self friendsListRequest];
        }
            break;
        case GroupMemberHandelTypeAdd:
        {
            [self friendsListRequestToAddGroupMember];
        }
            break;
        case GroupMemberHandelTypeDelete:
        {
            [self friendsListRequestToDeleteGroupMember];
        }
            break;
        default:
            break;
    }
    
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 66;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 66)];
    bgView.backgroundColor = [UIColor globalBackgroundColor];
    self.headerView = [[AddGroupHeaderView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH-30, 46)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.headerView.dataArr = self.selectArr;

    [bgView addSubview:self.headerView];
    return bgView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddGroupChatCell *cell = [AddGroupChatCell cellWithTableView:tableView];
    Friends *model = self.dataArr[indexPath.row];
    
    switch (self.groupMemberHandelType) {
        case GroupMemberHandelTypeAdd:
        {
            //判断是否是群成员
            if (model.isMember == YES) {
                cell.userInteractionEnabled = NO;
                cell.unableSelectView.hidden = NO;
            } else if (model.isMember == NO){
                cell.unableSelectView.hidden = YES;
                cell.userInteractionEnabled = YES;;
            }
        }
            break;
        default:
            break;
    }
   
    cell.friendListModel = model;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    int selectCount = 0;
    [self.selectArr removeAllObjects];
    for (int i = 0; i < self.dataArr.count; i++) {
        Friends *model = self.dataArr[i];
        if (i == indexPath.row) {
            model.isSelect = !model.isSelect;
        }
        //添加头部已选中数据数组
        if (model.isSelect == YES) {
            [self.selectArr addObject:model];
        }
    }
    if (selectCount == 0) {
        [self.completeBtn setTitle:@"完成" forState:UIControlStateNormal];
    } else {
        [self.completeBtn setTitle:[NSString stringWithFormat:@"完成(%d)",selectCount] forState:UIControlStateNormal];
    }
    [self.myTableView reloadData];
    
}
#pragma mark - target action
- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)completeBtnClick {
    switch (self.groupMemberHandelType) {
        case GroupMemberHandelTypeCreate:
        {
            [self createTGroup];
        }
            break;
        case GroupMemberHandelTypeAdd:
        {
            [self addGroupMemberRequest];
        }
            break;
        case GroupMemberHandelTypeDelete:
        {
            [self deleteRequest];
        }
            break;
        default:
            break;
    }
}
#pragma mark - private method

#pragma mark --------- 创建群聊 -------
//创建群组，获取好友列表
- (void)friendsListRequest {
    //获取好友列表数据
    @weakify(self);
    [[[PigMarketApi sharedInstance] myFriendsListWithMemberId:[UserInfoDataProvider sharedInstance].userInfo.memberId nickName:@"" currentPage:1] subscribeNext:^(FriendsList * _Nullable friendList) {
        
        @strongify(self);
        
        if (![JTool iSNull:friendList.list]) {
            for (Friends *model in friendList.list) {
                model.isSelect = NO;
            }
            [self.dataArr addObjectsFromArray:friendList.list];
        }
        [self.myTableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
//TIM创建群聊
- (void)createTGroup {
    NSMutableArray *memberArr = [[NSMutableArray alloc] init];
    //获取当前登录用户
    NSString *groupName = [[TIMManager sharedInstance] getLoginUser];

    for (Friends *model in self.selectArr) {
        TIMCreateGroupMemberInfo *member = [[TIMCreateGroupMemberInfo alloc] init];
        member.member = model.memberNum;
        member.role = TIM_GROUP_MEMBER_ROLE_MEMBER;
        [memberArr addObject:member];
        groupName = [NSString stringWithFormat:@"%@、%@", groupName, model.nickName];
    }
    NSString *tempStr = groupName;
    if (groupName.length > 10) {
        tempStr = [groupName substringToIndex:10].mutableCopy;
    }
    TIMCreateGroupInfo *info = [[TIMCreateGroupInfo alloc] init];
    info.groupType = @"Public";
    info.groupName = tempStr;
    info.setAddOpt = YES;
    info.addOpt = TIM_GROUP_ADD_ANY;
    info.membersInfo = memberArr;
    
    @weakify(self);
    [[TIMGroupManager sharedInstance] createGroup:info succ:^(NSString *groupId) {
        
        @strongify(self);
        TIMMessage *tip = [[TIMMessage alloc] init];
        TIMCustomElem *custom = [[TIMCustomElem alloc] init];
        custom.data = [@"group_create" dataUsingEncoding:NSUTF8StringEncoding];
        custom.ext = [NSString stringWithFormat:@"\"%@\"创建群组", [[TIMManager sharedInstance] getLoginUser]];
        [tip addElem:custom];
        
        TIMConversation *conv = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:groupId];
        [conv sendMessage:tip succ:nil fail:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            TUIConversationCellData *data = [[TUIConversationCellData alloc] init];
            data.convId = groupId;
            data.convType = TIM_GROUP;
            data.title = groupName;
            ChatViewController *chat = [[ChatViewController alloc] init];
            chat.conversation = data;
            [self.navigationController pushViewController:chat animated:YES];
        });
    } fail:^(int code, NSString *msg) {
        [self toastWithContent:msg];
    }];
}
#pragma mark --------- 添加群成员 -------
//获取群成员列表数据
- (void)friendsListRequestToAddGroupMember {
    //获取好友列表数据
    @weakify(self);
    [[[PigMarketApi sharedInstance] myFriendsListWithMemberId:[UserInfoDataProvider sharedInstance].userInfo.memberId nickName:@"" currentPage:1] subscribeNext:^(FriendsList * _Nullable friendList) {
        
        @strongify(self);
        if (![JTool iSNull:friendList.list]) {
            for (Friends *friendModel in friendList.list) {
                //获取群成员数据
                for (int i = 0 ; i < self.headerMemberInfoArr.count; i ++) {
                    TGroupMemberCellData *memberModel = self.headerMemberInfoArr[i];
                    if ([memberModel.identifier isEqualToString:friendModel.memberNum]) {
                        friendModel.isMember = YES;
                        break;
                    } else {
                        friendModel.isMember = NO;
                    }
                }
            }
            [self.dataArr addObjectsFromArray:friendList.list];
        }
        [self.myTableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}

//添加群成员本地接口请求
- (void)addGroupMemberRequest{
    NSMutableArray *membersArr = [[NSMutableArray alloc] init];
    for (Friends *model in self.selectArr) {
        [membersArr addObject:model.memberNum];
    }
    
    NSString *str = [NSString stringWithFormat:@"%@ 申请加入群聊", membersArr[0]];

    [[TIMGroupManager sharedInstance] joinGroup:self.identifier msg:str succ:^{
        [self toastWithContent:@"ok"];

    } fail:^(int code, NSString *msg) {
        [self toastWithContent:msg];

    }];
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] addGroupMemberWithGroupId:self.identifier memberList:membersArr] subscribeNext:^(NSNull * _Nullable x) {

        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError * _Nullable error) {

        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark --------- 删除群成员 -------
//删除群成员列表数据
- (void)friendsListRequestToDeleteGroupMember {
    //获取群成员数据
    for (int i = 0 ; i < self.headerMemberInfoArr.count; i ++) {
        TGroupMemberCellData *memberModel = self.headerMemberInfoArr[i];
        Friends *friendModel = [[Friends alloc] init];
        friendModel.headImage = memberModel.avatar;
        friendModel.nickName = memberModel.name;
        friendModel.memberNum = memberModel.identifier;
        [self.dataArr addObject:friendModel];
    }
    [self.myTableView reloadData];
}
//删除本地接口请求
- (void)deleteRequest{
    NSMutableArray *deleteArr = [[NSMutableArray alloc] init];
    for (Friends *model in self.selectArr) {
        [deleteArr addObject:model.memberNum];
    }
    @weakify(self);
    [[[PigMarketApi sharedInstance] deleteGroupMemberWithGroupId:self.identifier memberList:deleteArr] subscribeNext:^(NSNull * _Nullable x) {
        
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.rowHeight = 70;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [[NSMutableArray alloc] init];
    }
    return _selectArr;
}
@end
